import Mock from 'mockjs';

// 创建内存数据库
const mockDatabase = (() => {
  // 生成用户数据
  const generateUsers = () => {
    return Mock.mock({
      'list|10-20': [
        {
          'id|+1': 1,
          'username': '@word(5, 10)',
          'name': '@cname',
          'email': '@email',
          'phone': /1[3-9]\d{9}/,
          'role': '@pick(["admin", "lawyer", "user"])',
          'avatar': '@image("100x100", "#4A7BF7", "Avatar")',
          'status|0-1': 0, // 0-正常, 1-禁用
          'createdAt': '@datetime',
          'lastLoginAt': '@datetime'
        }
      ]
    }).list;
  };

  return {
    users: generateUsers(),
    currentUser: null,
    tokens: new Map()
  };
})();

/**
 * 认证模块Mock配置
 * @param {MockAdapter} mock - Mock适配器实例
 */
export default function(mock) {
  // 用户登录
  mock.onPost('/auth/login').reply(config => {
    const { username, password } = JSON.parse(config.data);
    
    // 模拟10%的服务器错误率
    if (Math.random() < 0.1) {
      return [500, { 
        code: 500, 
        message: '服务器内部错误，请稍后重试' 
      }];
    }
    
    const user = mockDatabase.users.find(u => 
      u.username === username || u.email === username || u.phone === username
    );
    
    // 模拟登录失败场景
    if (!user) {
      return [401, { 
        code: 401, 
        message: '用户名或密码错误' 
      }];
    }
    
    if (user.status !== 0) {
      return [403, { 
        code: 403, 
        message: '账户已被禁用，请联系管理员' 
      }];
    }
    
    // 密码验证（简单实现）
    const passwordValid = password.length >= 6;
    if (!passwordValid) {
      return [401, { 
        code: 401, 
        message: '用户名或密码错误' 
      }];
    }
    
    // 生成token
    const token = `mock_jwt_token_${Date.now()}_${user.id}`;
    const expires = 3600 * 24 * 7; // 7天有效期
    
    // 存储token和用户关系
    mockDatabase.tokens.set(token, {
      userId: user.id,
      expires: Date.now() + expires * 1000
    });
    
    // 更新用户最后登录时间
    user.lastLoginAt = new Date().toISOString();
    mockDatabase.currentUser = user;
    
    return [200, {
      code: 200,
      message: '登录成功',
      data: {
        token,
        expires,
        user: {
          id: user.id,
          username: user.username,
          name: user.name,
          email: user.email,
          phone: user.phone,
          role: user.role,
          avatar: user.avatar,
          status: user.status
        }
      }
    }];
  });

  // 用户注册
  mock.onPost('/auth/register').reply(config => {
    const userData = JSON.parse(config.data);
    
    // 检查用户名是否已存在
    const existingUser = mockDatabase.users.find(u => 
      u.username === userData.username || u.email === userData.email
    );
    
    if (existingUser) {
      return [400, { 
        code: 400, 
        message: '用户名或邮箱已存在' 
      }];
    }
    
    // 创建新用户
    const newUser = {
      id: Math.max(...mockDatabase.users.map(u => u.id)) + 1,
      ...userData,
      role: 'user', // 默认角色
      status: 0, // 默认正常状态
      avatar: Mock.Random.image('100x100', '#4A7BF7', 'Avatar'),
      createdAt: new Date().toISOString(),
      lastLoginAt: null
    };
    
    mockDatabase.users.push(newUser);
    
    return [201, { 
      code: 201, 
      message: '注册成功',
      data: {
        id: newUser.id,
        username: newUser.username,
        name: newUser.name,
        email: newUser.email
      }
    }];
  });

  // 获取当前用户信息
  mock.onGet('/auth/current-user').reply(config => {
    const token = config.headers['sa-token'] || config.headers['Authorization'];
    
    if (!token) {
      return [401, { 
        code: 401, 
        message: '未提供认证令牌' 
      }];
    }
    
    const tokenData = mockDatabase.tokens.get(token.replace('Bearer ', ''));
    
    if (!tokenData || Date.now() > tokenData.expires) {
      return [401, { 
        code: 401, 
        message: '认证令牌已过期' 
      }];
    }
    
    const user = mockDatabase.users.find(u => u.id === tokenData.userId);
    
    if (!user) {
      return [404, { 
        code: 404, 
        message: '用户不存在' 
      }];
    }
    
    return [200, {
      code: 200,
      data: {
        id: user.id,
        username: user.username,
        name: user.name,
        email: user.email,
        phone: user.phone,
        role: user.role,
        avatar: user.avatar,
        status: user.status,
        createdAt: user.createdAt,
        lastLoginAt: user.lastLoginAt
      }
    }];
  });

  // 用户登出
  mock.onPost('/auth/logout').reply(config => {
    const token = config.headers['sa-token'] || config.headers['Authorization'];
    
    if (token) {
      mockDatabase.tokens.delete(token.replace('Bearer ', ''));
    }
    
    mockDatabase.currentUser = null;
    
    return [200, {
      code: 200,
      message: '登出成功'
    }];
  });

  // 刷新token
  mock.onPost('/auth/refresh').reply(config => {
    const { refreshToken } = JSON.parse(config.data);
    
    // 简单的token刷新逻辑
    const newToken = `mock_jwt_token_${Date.now()}_refreshed`;
    const expires = 3600 * 24 * 7; // 7天有效期
    
    return [200, {
      code: 200,
      message: 'Token刷新成功',
      data: {
        token: newToken,
        expires
      }
    }];
  });

  // 修改密码
  mock.onPost('/auth/change-password').reply(config => {
    const { oldPassword, newPassword } = JSON.parse(config.data);
    
    if (oldPassword.length < 6 || newPassword.length < 6) {
      return [400, { 
        code: 400, 
        message: '密码长度不能少于6位' 
      }];
    }
    
    return [200, {
      code: 200,
      message: '密码修改成功'
    }];
  });

  // 忘记密码
  mock.onPost('/auth/forgot-password').reply(config => {
    const { email } = JSON.parse(config.data);
    
    const user = mockDatabase.users.find(u => u.email === email);
    
    if (!user) {
      return [404, { 
        code: 404, 
        message: '该邮箱未注册' 
      }];
    }
    
    return [200, {
      code: 200,
      message: '重置密码邮件已发送，请查收邮箱'
    }];
  });
} 